import { getFullTreeByXid, s_getPostWareInfo, s_getSelectData, s_getSelectTree, s_operateInfo, s_updateInfo } from "@/services/basis";
import { ActionType, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormInstance, ProFormItem, ProFormRadio, ProFormSelect, ProFormText, ProTable, TableDropdown } from "@ant-design/pro-components";
import { useModel, useRequest } from "@umijs/max";
import { Button, Card, Col, Form, message, Modal, Row, Select, Space, Table, TableColumnProps, Tabs, TabsProps, Tag, Typography } from "antd";
import { isNull, isNumber } from "lodash";
import moment from "moment";
import React, { useRef, useState } from "react";

const App:React.FC=()=>{
    const [selectedRowKeys,setSelectedRowKeys]=useState<React.Key[]>([]);
    const [selectedRows,setSelectedRows]=useState<DataType[]>([]);
    const [open,setOpen]=useState(false);

    const [selectedRowKeys2,setSelectedRowKeys2]=useState<React.Key[]>([]);
    const [selectedRows2,setSelectedRows2]=useState<DataType2[]>([]);
    const [open2,setOpen2]=useState(false);

    const [tabKey,setTabKey]=useState('1');
    const [etype,setEtype]=useState(1);
    // const [areaSelect,setAreaSelect]=useState([]);

    const table_ref=useRef<ActionType>();
    const table_ref2=useRef<ActionType>();
    const form_ref=useRef<ProFormInstance>();
    const form_ref2=useRef<ProFormInstance>();

    const { initialState, setInitialState } = useModel('@@initialState');
    const [selectedLineKeys,setSelectedLineKeys]=useState<any[]>([]);

    // useRequest(async ()=>await s_getSelectTree({x_id:1,source:'base_area'}),{
    //     onSuccess:(data)=>setAreaSelect(data),
    // });


    interface DataType{
        x_id:number,
        id:number,
        code:string,
        name:string,
        company:string,
        type:number,
        area_id?:number,
        area_name?:string,
        postcode_id?:number,
        postcode_code?:string,
        country?:string,
        province?:string,
        city?:string,
        address?:string,
        isfar?:number,
        operate_time:string,
        operater_name:string,
        status:number,
    }
    const columns:ProColumns<DataType>[]=[
        {key:'id',dataIndex:'id',title:'ID'},{dataIndex:'x_id',hidden:true},
        {dataIndex:'code',title:'仓库编码'},{dataIndex:'name',title:'仓库名'},{dataIndex:'company',title:'公司'},
        {dataIndex:'type',title:'类型',valueType:'radio',
            valueEnum:{1:{text:'普通仓'},2:{text:'线边仓'},3:{text:'VMI仓'}}
        },
        {dataIndex:'area_id',hidden:true},{dataIndex:'postcode_id',hidden:true},
        {dataIndex:'area_name',title:'区域'},{dataIndex:'postcode_code',title:'邮编'},
        {dataIndex:'country',title:'国家'},{dataIndex:'province',title:'省/州'},{dataIndex:'city',title:'城'},
        {dataIndex:'address',title:'详细地址'},
        {dataIndex:'isfar',title:'是否偏远',render:(text:any)=>text==0||(!isNumber(text))?<></>:<Tag style={{color:'red'}}>是</Tag>},
        {dataIndex:'operate_time',title:'修改时间',
            render:(text)=>moment(moment(text?.toString()).toDate()).format('YYYY-MM-DD')},
        {dataIndex:'operater_name',title:'修改人'},
        {dataIndex:'status',title:'状态',
            render:(text)=>text==1?<>正常</>:text==2?<Tag style={{color:'blue'}}>关闭</Tag>:<Tag style={{color:'red'}}>删除</Tag>},
    ];

    interface DataType2{
        x_id:number,
        id:number,
        code:string,
        name:string,
        groups:string,
        status:number,
        operater_name:string,
        operate_time:string,
    }
    const columns2:ProColumns<DataType2>[]=[
        {dataIndex:'x_id',hidden:true},
        {dataIndex:'id',title:'ID',key:'id'},
        {dataIndex:'code',title:'组编号',},
        {dataIndex:'name',title:'组名称',},
        {dataIndex:'groups',title:'详细仓库编码',},
        {dataIndex:'operate_time',title:'操作时间',
            render:(text)=>moment(moment(text?.toString()).toDate()).format('YYYY-MM-DD')
        },
        {dataIndex:'operater_name',title:'操作人',},
        {dataIndex:'status',title:'状态',
            render:(text)=>text==1?<>正常</>:text==2?<Tag style={{color:'blue'}}>关闭</Tag>:<Tag style={{color:'red'}}>删除</Tag>}
        
    ];
    
    const items:TabsProps['items']=[
      {
        key:'1',
        label:'仓库档案',
        children:<>
        {/* {JSON.stringify(selectedRows)} */}
            <ProTable<DataType>
                rowKey='id'
                actionRef={table_ref}
                search={false}
                columns={columns}
                rowSelection={{
                    type:'radio',
                    onChange:(selectedRowKeys,selectedRows)=>{
                            setSelectedRowKeys(selectedRowKeys);
                            setSelectedRows(selectedRows);
                    },
                }}
                request={async (params)=>{
                    //const id=selectedRowKeys.length==0?0:selectedRowKeys[0];
                    const x=await s_getPostWareInfo({source:'v_ware',x_id:1,id:0})
                    return{
                        data:x.data,
                        success:true,
                    }
                }}
                scroll={{
                    y:430,
                }}
                pagination={{
                    pageSize:9,
                }}
                />
        </>
      },
    //   {
    //      key:'2',
    //      label:'仓库分组',
    //      children:<>
    //        <ProTable<DataType2>
    //         rowKey='id'
    //          search={false}
    //          actionRef={table_ref2}
    //          columns={columns2}
    //          rowSelection={{
    //              type:'radio',
    //              onChange:(selectedRowKeys,selectedRows)=>{
    //                      setSelectedRowKeys2(selectedRowKeys);
    //                      setSelectedRows2(selectedRows);
    //              },
    //          }}
    //          request={async (params)=>{
    //              //const id=selectedRowKeys.length==0?0:selectedRowKeys[0];
    //              const x=await s_getPostWareInfo({source:'v_ware_group',x_id:1,id:0})
    //              return{
    //                  data:x.data,
    //                  success:true,
    //              }
    //          }}
    //          scroll={{
    //             y:430,
    //         }}
    //         pagination={{
    //             pageSize:9,
    //         }}
    //        />
    //      </>
    //   },
    ];

    async function add(){
        setEtype(1);
        if(tabKey=='1'){
          setOpen(true);
          setOpen2(false);
        }else{
            setOpen2(true);
            setOpen(false);
          }
    };
    async function edit(){
        if(tabKey=='1'){
            // setSelectedRows2([]);
           if(selectedRows.length==0)
              message.warning('请先选择要编辑的行。');
            else if(selectedRows[0].status==2||selectedRows[0].status==3)
                message.warning('已删除或关闭的档案，不能编辑。');
            else{
                // alert('6666');
                setOpen(true);
                setOpen2(false);
                setEtype(0);
            }
        }else{
            // setSelectedRows([]);
            if(selectedRows2.length==0)
                message.warning('请先选择要编辑的行。');
              else{
                //   alert(tabKey);
                  setOpen2(true);
                  setOpen(false);
                  setEtype(0);
              }
        }
    };

    async function save(){
        if(tabKey=='1'){
           const fdata2=form_ref?.current?.getFieldsValue();
           const fdata={...fdata2,
                 operate_time:moment().format('YYYY-MM-DD HH:00:00'),
           };
           const x=await s_updateInfo({source:'base_ware',x_id:1,
                      operater_id:initialState?.currentUser?.userid,etype,fdata});
           
           if(x.success){
              message.success('数据保存成功。');
              setOpen(false);
              table_ref.current?.reloadAndRest?.();
              setSelectedRows([]);
              setSelectedRowKeys([]);
              setEtype(1);
           }else
           message.error('数据保存失败。');
        }else{
        //组保存
        const fdata2=form_ref2?.current?.getFieldsValue();
        const fdata={...fdata2,
              operate_time:moment().format('YYYY-MM-DD HH:00:00'),
        };
        const x=await s_updateInfo({source:'base_ware_group',x_id:1,operater_id:initialState?.currentUser?.userid,etype,fdata});
        if(x.success){
           message.success('数据保存成功。');
           setOpen2(false);
           table_ref2.current?.reloadAndRest?.();
           setSelectedRows2([]);
           setSelectedRowKeys2([]);
           setEtype(1);
        }else
        message.error('数据保存失败。');
        }
    };

    async function operate(otype:number){
          setEtype(1);
          var id=0;
          if(tabKey=='1'){
             if(selectedRows.length==0)
                 message.warning('请先选择要操作的行。');
             else{
                 id=selectedRows[0].id;
                const x=await s_operateInfo({source:'base_ware',x_id:1,operater_id:initialState?.currentUser?.userid,otype,id});
                if(x.success){
                    message.success('数据更新成功。');
                    table_ref.current?.reloadAndRest?.();
                    setSelectedRows([]);
                    setSelectedRowKeys([]);
                }
                else
                    message.error('数据更新失败。');
                
               }
        }
        else{
            if(selectedRows2.length==0)
                message.warning('请先选择要操作的行。');
            else{
                id=selectedRows2[0].id;
                const x=await s_operateInfo({source:'base_ware_group',x_id:1,operater_id:initialState?.currentUser?.userid,otype,id});
                if(x.success){
                    message.success('数据更新成功。');
                    table_ref2.current?.reloadAndRest?.();
                    setSelectedRows2([]);
                    setSelectedRowKeys2([]);
                }
                else
                    message.error('数据更新失败。');
               }
        }
     };   

    return (
        <>
        <ProCard title='仓库管理' style={{height:'75vh',overflow:'auto'}} 
              extra={<Space>
                <Button onClick={()=>add()}>新 增</Button>
                <Button onClick={()=>edit()}>编 辑</Button>
                <Button onClick={()=>operate(2)}>关闭</Button>
                <Button onClick={()=>operate(3)}>删 除</Button>
                <Button onClick={()=>operate(1)}>恢 复</Button>
               </Space>}
        >
       {/* <Tabs items={items} 
            onChange={(e)=>{
                 setTabKey(e);
                 setEtype(1);
            }} 
        /> */}
        <ProTable<DataType>
                rowKey='id'
                actionRef={table_ref}
                search={false}
                columns={columns}
                rowSelection={{
                    type:'radio',
                    selectedRowKeys:selectedLineKeys,
                    onChange:(selectedRowKeys,selectedRows)=>{
                            setSelectedRowKeys(selectedRowKeys);
                            setSelectedRows(selectedRows);
                            setSelectedLineKeys(selectedRowKeys);
                    },
                }}
                 onRow={(record)=>{
                   return {
                     onClick:()=>{
                      const k=record.id;
                // if(selectedKeys.includes(k) )
                //      setSelectedKeys(selectedKeys.filter(item=>item.id!=k));
                // else
                     setSelectedRowKeys([k]);
                     setSelectedRows([record]);
                     setSelectedLineKeys([k]);
              },
            }
           }}
                request={async (params)=>{
                    //const id=selectedRowKeys.length==0?0:selectedRowKeys[0];
                    const x=await s_getPostWareInfo({source:'v_ware',x_id:1,id:0})
                    return{
                        data:x.data,
                        success:true,
                    }
                }}
                scroll={{
                    y:'55vh',
                }}
                options={false}
                />
        </ProCard>
        {/* 档案增减表单 */}
        <Modal open={open} title={etype==0?'编辑仓库档案':'新增仓库档案'} closable destroyOnClose onCancel={()=>setOpen(false)}
            onOk={()=>form_ref.current?.submit()} width={660}>
           <ProForm 
                   formRef={form_ref} 
                   submitter={false}
                   onFinish={()=>save()}
                   initialValues={etype==0&&tabKey=='1'?{
                   ...selectedRows[0],
                   operate_time:moment(moment(selectedRows[0].operate_time).toDate()).format('YYYY-MM-DD'),
                 }:{
                    operate_time:moment().format('YYYY-MM-DD'), status:1,isfar:0,type:1,
                    operater_id:initialState?.currentUser?.userid
                  }}
           >
            <Row gutter={16}>
                <Col span={12}>
                   <ProFormText name='code' label='编码' rules={[{required:true,message:'必输项'}]}/>
                </Col>
                <Col span={12}>
                <ProFormText name='name' label='名称' rules={[{required:true,message:'必输项'}]}/>
                </Col>
            </Row>
            <Row gutter={8}>
                <Col span={12}>
                <ProFormRadio.Group name='type' label='类型'  rules={[{required:true,message:'必输项'}]}
                options={[{label:'普通仓',value:1},{label:'线边仓',value:2},{value:3,label:'VMI仓'}]}
             /> 
                </Col>
                <Col span={12}>
                <ProFormSelect name='area_id' label='地区'
                 showSearch
                 request={async ()=>{
                    const x=await s_getSelectData({x_id:1,source:'base_area'});
                    return x.data;
             }}
             />
                </Col>
            </Row>
            <Row gutter={8}>
                <Col span={12}>
                <ProFormSelect name='postcode_id' label='邮编'
                 showSearch
                 request={async ()=>{
                    const x=await s_getSelectData({x_id:1,source:'base_postcode'});
                    return x.data;
             }}
             />
                </Col>
                <Col span={12}>
                <ProFormText name='company' label='公司'/>
                </Col>
            </Row>
            <Row gutter={8}>
                <Col span={12}>
                <ProFormText name='address' label='详细地址'/>
                </Col>
                <Col span={12}>
                <ProFormRadio.Group name='status' label='状态'
                options={[{label:'正常',value:1},{label:'关闭',value:2,style:{color:'blue'}},{label:'删除',value:3,style:{color:'red'}}]}
             />
                </Col>
            </Row>
            <Row gutter={8}>
                <Col span={12}>
                <ProFormDatePicker name='operate_time' label='操作时间'/>
                </Col>
                <Col span={12}>
                 <ProFormSelect name='operater_id' label='操作人' width={300}
                    showSearch
                     request={async ()=>{
                        const x=await s_getSelectData({x_id:1,source:'base_person'});
                        return x.data;}}
                 />
                </Col>
            </Row>
             <ProFormText name='x_id' hidden/>
             <ProFormText name='id' hidden/>
               </ProForm>
        </Modal>
         {/* 档案组--增减表单 */}
         <Modal open={open2} title={etype==0?'编辑仓库组':'新增仓库组'} closable destroyOnClose onCancel={()=>setOpen2(false)}
            onOk={()=>form_ref2.current?.submit()} width={500}>
           <ProForm 
                   formRef={form_ref2} 
                   submitter={false}
                   onFinish={()=>save()}
                   initialValues={etype==0&&tabKey=='2'?{
                    ...selectedRows2[0],
                    operate_time:moment(moment(selectedRows2[0].operate_time).toDate()).format('YYYY-MM-DD'),
                  }:{
                     operate_time:moment().format('YYYY-MM-DD'),operater_name:'张飞飞',status:1,
                   }}
           >
             <ProFormText name='id' hidden/>
             <ProFormText name='x_id' hidden/>
             <ProFormText name='code' label='编码' rules={[{required:true,message:'必输项'}]}/>
             <ProFormText name='name' label='名称' rules={[{required:true,message:'必输项'}]}/>
             <ProFormText name='groups' label='组成员代码/请以-进行分隔。示例：A-B-C' placeholder='A-B-C-D' rules={[{required:true,message:'必输项'}]}/>
             <ProFormRadio.Group name='status' label='状态'
                options={[{label:'正常',value:1},{label:'关闭',value:2,style:{color:'blue'}},{label:'删除',value:3,style:{color:'red'}}]}
             />
             <ProFormDatePicker name='operate_time' label='操作时间'/>
              <ProFormSelect name='operater_id' label='操作人' width={300}
                    showSearch
                     request={async ()=>{
                        const x=await s_getSelectData({x_id:1,source:'base_person'});
                        return x.data;}}
                 />
           </ProForm>
        </Modal>
        </>
    );
}

export default App;